﻿using System.Diagnostics;
using MusicManagerDAO.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MusicManagerDAO.Implementation
{
    public class UserDao : IUserDao
    {
        static UserDao()
        {
            using (MusicManagerDbContext ctx = new MusicManagerDbContext())
            {
                // richTextBox.AppendText("StockDao: using connction string \"{0}\"", ctx.Database.Connection.ConnectionString);
                Trace.WriteLine(String.Format("StockDao: using connction string \"{0}\"", ctx.Database.Connection.ConnectionString), "Information");
            }
        }

        public DomainModel.User FindByNameAndPassword(string name, string password)
        {
            using (MusicManagerDbContext ctx = new MusicManagerDbContext())
            {
                var query = from s in ctx.Users
                            where s.Name == name && s.Password == password
                            select s;
                return query.FirstOrDefault().ToDomain();
            }
        }

        public IEnumerable<DomainModel.User> FindAll()
        {
            using (MusicManagerDbContext ctx = new MusicManagerDbContext())
            {
                var query = (from s in ctx.Users.AsEnumerable()
                             select s.ToDomain());
                return query.ToList();
            }
        }

        public bool Insert(DomainModel.User user)
        {
            if (UserExists(user.Id))
                return false;

            using (MusicManagerDbContext ctx = new MusicManagerDbContext())
            {
                ctx.Users.Add(user.ToEF());
                ctx.SaveChanges();
                return true;
            }
        }

        private bool UserExists(int p)
        {
            using (MusicManagerDbContext ctx = new MusicManagerDbContext())
            {
                return ctx.Users.Where(s => s.Id == p).FirstOrDefault() != null;
            }
        }


        public IEnumerable<DomainModel.User> FindByNameLike(string contain)
        {
            using (MusicManagerDbContext ctx = new MusicManagerDbContext())
            {
                IQueryable<User> qResult = ctx.Users.Where(u => u.Name.Contains(contain));
                List<DomainModel.User> result = new List<DomainModel.User>();
                foreach(User daoUser in qResult.ToList())
                {
                    result.Add(daoUser.ToDomain());
                }
                return result;
            }
        }
    }
}
